package com.exp.bookhouse.controller;

import com.exp.bookhouse.mapper.UserMapper;
import com.exp.bookhouse.pojo.MyUser;
import com.exp.bookhouse.pojo.Role;
import com.exp.bookhouse.pojo.vo.UserVo;
import com.exp.bookhouse.security.SecurityService;
import com.exp.bookhouse.service.RoleService;
import com.exp.bookhouse.service.UserService;
import com.exp.bookhouse.util.ApiJSONResult;
import com.exp.bookhouse.util.RedisUtil;
import com.exp.bookhouse.util.UploadService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@Api(value = "用户接口",tags = "用户操作")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${nginx.port}")
    private String port;

    @Value("${nginx.host}")
    private String host;

    @Value("${nginx.group}")
    private String group;

    @Autowired
    private RoleService roleService;

    @Autowired
    private SecurityService securityService;


    @Autowired
    private UserMapper userMapper;


    /**
     * 用户登录
     * paramType:
     * header：请求参数放置于Request Header，使用@RequestHeader获取
     * query：请求参数放置于请求地址，使用@RequestParam获取
     * path：（用于restful接口）-->请求参数的获取：@PathVariable
     *
     * @param encryptedData 明文,加密数据
     * @param iv            加密算法的初始向量
     * @param code          用户允许登录后，回调内容会带上 code（有效期五分钟），开发者需要将 code 发送到开发者服务器后台，
     *                      使用code 换取 session_key api，将 code 换成 openid 和 session_key
     * @return 用户信息
     */
    @ApiOperation(value = "微信登录", notes = "微信用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "encryptedData", value = "明文", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "iv", value = "加密算法的初始向量", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "code", value = "临时登录凭证", required = true, dataType = "String")
    })
    @PostMapping(value = "/decodeUser")
    public ApiJSONResult weChatLogin(String encryptedData, String iv, String code, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(encryptedData + iv + code)) {
            throw new Exception("参数不能为空");
        }
        MyUser myUser = userService.weChatLogin(encryptedData, iv, code);//微信用户登录验证

        List<Role> roles = userMapper.queryRoles(myUser.getId());//获取角色身份
        if(roles.isEmpty()){//新用户添加角色
            Role role =  roleService.queryRoleByRoleName("ROLE_USER");
            userMapper.saveUserRole(myUser.getId(),role.getId());
        }

        String uniqueToken = UUID.randomUUID().toString();
        redisUtil.set("user_redis_session"+":"+ myUser.getId(),uniqueToken,1000*60*30); //1000*30分钟

        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(myUser, userVo); //复制myUser 到 userVo中
        userVo.setUserToken(uniqueToken);

        return ApiJSONResult.ok(userVo);
    }



//    /**
//     * 用户更新
//     * @param myUser 用户对象
//     * @return 成功与否
//     */
//    @ApiOperation(value = "用户更新", notes = "用户更新")
////    @PutMapping
//    @PostMapping("/updateUser")
//    public ApiJSONResult updateUser(@ApiParam(value = "用户对象", required = true) MyUser myUser) {
//        System.out.println("=============myuser=========="+myUser);
//        int b = userService.updateUser(myUser);
//        if (b == 1) {
//            return ApiJSONResult.ok("更新成功");
//        }else{
//            return ApiJSONResult.errorMsg("更新失败");
//        }
//    }



    /**
     * 文件上传
     * @param file   上传的文件
     * @param userId 用户id
     * @return StorePath
     * @deprecated 文件上传
     * storePath
     * "group": "group1",
     * "path": "M00/00/01/wKj4RFvuZlOALpzMAAJZc0IRPSY16.jpg",
     * fullPath": "group1/M00/00/01/wKj4RFvuZlOALpzMAAJZc0IRPSY16.jpg"
     */
    @ApiOperation(value = "文件上传", notes = "根据用户id上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "headImage", value = "用户当前的头像url", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping(value = "/upload")
    public ApiJSONResult uploadFileAndUserId(@ApiParam(value = "上传的文件", required = true) MultipartFile file, Long userId, String headImage) throws Exception {
        /* 设置文件信息 */
        if (StringUtils.isBlank(userId.toString())) {
            throw new Exception("userId不能为空");
        }

        if (file == null) {
            throw new Exception("文件不能为空");
        }
//        http://qlwdwvwug.hn-bkt.clouddn.com/bookstore/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20181019122851_20205726025701.jpg
        String fullUrl = uploadService.uploadFile(file);   //上传文件返回不带分组路径
//        String fullUrl = "http://"+host+":"+port+"/"+path;   //全路径
        int count = userService.updateHeadImage(userId,fullUrl);    //保存数据库
        if(count == 0){
            throw new Exception("头像更新失败");
        }

        //删除服务器的图片
        if(headImage.contains(group)){
            String[] split = headImage.split(".com/");
            uploadService.deleteFile(split[1]);
        }
        return ApiJSONResult.ok(fullUrl);
    }

    /**
     * 用户更新
     * @param myUser 用户对象
     * @return 成功与否
     */
    @ApiOperation(value = "用户更新", notes = "用户更新")
//    @PutMapping
    @PostMapping("/updateUser")
    public ApiJSONResult updateUser(@ApiParam(value = "用户对象", required = true) MyUser myUser) {
        System.out.println("=============myuser=========="+myUser);
        int b = userService.updateUser(myUser);
        if (b == 1) {
            return ApiJSONResult.ok("更新成功");
        }else{
            return ApiJSONResult.errorMsg("更新失败");
        }
    }
}
